import sqlite3
from common.log import log
from settings import ENV, DBSql


class MysqlAuto(object):
    def __init__(self):
        """连接到SQLite数据库"""
        self.conn = sqlite3.connect(DBSql.sql_file)
        # 创建Cursor对象并作为属性，用于执行SQL命令
        self.cursor = self.conn.cursor()
        log.info(f"Connect to database:{DBSql.sql_file}")

    def __del__(self):
        """对象资源释放时触发，在对象即将被删除时最后操作"""
        # 关闭游标和连接
        self.cursor.close()
        self.conn.close()
        log.info(f"Database connection closed.")

    def execute(self, sql_list):
        """执行sql语句"""
        global result
        try:
            for i in sql_list:  # 语句列表
                log.info(f'sql： {i}')
                self.cursor.execute(i)
                result = self.cursor.fetchall()
                log.debug(result)
            # 提交事务
            self.conn.commit()
            return result
        except Exception as e:
            log.error(f'执行sql出现错误，异常为{e}')
            raise e


if __name__ == '__main__':
    sqlite = MysqlAuto()
    res = sqlite.execute(['select * from df_user_userinfo'])
    print(res)
    # sqlite.execute(DBSql.sql_list)
